package com.xlt.activiti.one;

import lombok.SneakyThrows;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.List;


public class ActivitiQueryBPMNFile {
    @SneakyThrows
    public  static void queryBPMNFile(){
        // 1.得到processEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        // 2.获取repositoryService
        RepositoryService repositoryService = processEngine.getRepositoryService();

        // 3.得到查询器
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
        // 4.设置查询条件

        // 5. 执行查询操作，查询出想要的流程定义
        List<ProcessDefinition> list = processDefinitionQuery.
                processDefinitionKey("holiday").orderByProcessDefinitionVersion().desc().list();
        // 6.部署的id号
        if (list!=null && list.size()>0){
            ProcessDefinition processDefinition = list.get(0);
            String deploymentId =  processDefinition.getDeploymentId();
            // 7. 通过repositoryService 方法实现读取png 信息 (输入流)
            // processDefinition.getDiagramResourceName() 图片资源名称获取
            // processDefinition.getResourceName() bpmn 文件
            String pngFileName = processDefinition.getDiagramResourceName();
            String pbmnFileName =  processDefinition.getResourceName();
            InputStream inputStream = repositoryService.getResourceAsStream(deploymentId,pngFileName);
            InputStream input_pbmn_stream = repositoryService.getResourceAsStream(deploymentId,pbmnFileName);
            // 8.构建输出流 outputstream
            OutputStream pngOutputStream = null;
            OutputStream bpmnOutputStream = null;
            try {
                pngOutputStream = new FileOutputStream("/Users/gedongliang/Desktop/test/" + processDefinition.getDiagramResourceName());
                bpmnOutputStream = new FileOutputStream("/Users/gedongliang/Desktop/test/" + processDefinition.getResourceName());
                // 9.输入流和输出流转换 commons-io
                IOUtils.copy(inputStream,pngOutputStream);
                IOUtils.copy(input_pbmn_stream,bpmnOutputStream);

                inputStream.close();
                input_pbmn_stream.close();

                pngOutputStream.close();
                bpmnOutputStream.close();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                // 10 关闭流

            }
        }
    }
}
